package org.qiandaosystem.qiandaosystemsource.service;

import lombok.RequiredArgsConstructor;
import org.qiandaosystem.qiandaosystemsource.common.ApiResponse;
import org.qiandaosystem.qiandaosystemsource.dto.SignActivityStatisticsDTO;
import org.qiandaosystem.qiandaosystemsource.entity.SignActivity;
import org.qiandaosystem.qiandaosystemsource.entity.SignRecord;
import org.qiandaosystem.qiandaosystemsource.entity.Student;
import org.qiandaosystem.qiandaosystemsource.entity.Teacher;
import org.qiandaosystem.qiandaosystemsource.entity.User;
import org.qiandaosystem.qiandaosystemsource.mapper.*;
import org.qiandaosystem.qiandaosystemsource.util.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class TeacherService {

    private final UserMapper userMapper;
    private final TeacherMapper teacherMapper;
    private final StudentMapper studentMapper;
    private final SignActivityMapper signActivityMapper;
    private final SignRecordMapper signRecordMapper;
    private final JwtUtil jwtUtil;

    @Transactional
    public ApiResponse<?> createNormalSignActivity(String jwt, LocalDateTime startTime, LocalDateTime endTime) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        SignActivity activity = new SignActivity();
        activity.setTeacherId(teacher.getId());
        activity.setType(SignActivity.SignType.normal);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        
        signActivityMapper.insert(activity);
        return ApiResponse.success("创建签到活动成功", activity);
    }

    @Transactional
    public ApiResponse<?> updateSignActivity(String jwt, Integer activityId, 
                                           LocalDateTime startTime, LocalDateTime endTime) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        SignActivity activity = signActivityMapper.findByIdAndTeacherId(activityId, teacher.getId());
        if (activity == null) {
            return ApiResponse.error("签到活动不存在");
        }

        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        
        signActivityMapper.update(activity);
        return ApiResponse.success("更新签到活动成功", activity);
    }

    @Transactional
    public ApiResponse<?> deleteSignActivity(String jwt, Integer activityId) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        if (signActivityMapper.delete(activityId, teacher.getId()) > 0) {
            return ApiResponse.success("删除签到活动成功", null);
        } else {
            return ApiResponse.error("签到活动不存在或已被删除");
        }
    }

    public ApiResponse<?> getAllSignActivities(String jwt) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        List<SignActivity> activities = signActivityMapper.findByTeacherId(teacher.getId());
        return ApiResponse.success(activities);
    }

    @Transactional
    public ApiResponse<?> createCodeSignActivity(String jwt, LocalDateTime startTime, 
                                               LocalDateTime endTime, String signCode) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        SignActivity activity = new SignActivity();
        activity.setTeacherId(teacher.getId());
        activity.setType(SignActivity.SignType.code);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setSecret(signCode);
        
        signActivityMapper.insert(activity);
        return ApiResponse.success("创建签到码签到活动成功", activity);
    }

    public ApiResponse<?> getSignActivitiesStatistics(String jwt) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        // 获取所有未删除的签到活动
        List<SignActivity> activities = signActivityMapper.findByTeacherId(teacher.getId());
        List<SignActivityStatisticsDTO> statisticsList = activities.stream()
                .map(activity -> generateStatistics(activity, teacher.getId()))
                .collect(Collectors.toList());

        return ApiResponse.success(statisticsList);
    }

    public ApiResponse<?> getSignActivityStatistics(String jwt, Integer activityId) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        SignActivity activity = signActivityMapper.findByIdAndTeacherId(activityId, teacher.getId());
        if (activity == null) {
            return ApiResponse.error("签到活动不存在或已被删除");
        }

        SignActivityStatisticsDTO statistics = generateStatistics(activity, teacher.getId());
        return ApiResponse.success(statistics);
    }

    private SignActivityStatisticsDTO generateStatistics(SignActivity activity, Integer teacherId) {
        SignActivityStatisticsDTO statistics = new SignActivityStatisticsDTO();
        statistics.setActivityId(activity.getId());
        statistics.setType(activity.getType());
        statistics.setStartTime(activity.getStartTime());
        statistics.setEndTime(activity.getEndTime());
        statistics.calculateTimeStatus();

        // 获取该教师的所有学生
        List<Student> allStudents = studentMapper.findByTeacherId(teacherId);
        statistics.setTotalStudents(allStudents.size());

        // 获取该活动的所有签到记录
        List<SignRecord> signRecords = signRecordMapper.findByActivityId(activity.getId());
        Map<Integer, SignRecord> signRecordMap = signRecords.stream()
                .collect(Collectors.toMap(SignRecord::getStudentId, record -> record));

        List<SignActivityStatisticsDTO.StudentSignInfo> signedStudents = new ArrayList<>();
        List<SignActivityStatisticsDTO.StudentSignInfo> unsignedStudents = new ArrayList<>();

        // 遍历所有学生，区分已签到和未签到
        for (Student student : allStudents) {
            User user = userMapper.findById(student.getUserId());
            SignActivityStatisticsDTO.StudentSignInfo studentInfo = new SignActivityStatisticsDTO.StudentSignInfo();
            studentInfo.setUserId(student.getUserId());
            studentInfo.setUsername(user.getUsername());
            studentInfo.setRealName(student.getRealName());

            SignRecord record = signRecordMap.get(student.getUserId());
            if (record != null) {
                studentInfo.setSignTime(record.getSignTime());
                signedStudents.add(studentInfo);
            } else {
                unsignedStudents.add(studentInfo);
            }
        }

        statistics.setSignedStudents(signedStudents);
        statistics.setUnsignedStudents(unsignedStudents);
        statistics.setSignedCount(signedStudents.size());
        statistics.setUnsignedCount(unsignedStudents.size());

        return statistics;
    }

    private User validateTeacher(String jwt) {
        String username = jwtUtil.extractUsername(jwt);
        User user = userMapper.findByUsername(username);
        if (user == null || !"teacher".equals(user.getRole())) {
            return null;
        }
        return user;
    }
    @Transactional
    public ApiResponse<?> createGestureSignActivity(String jwt, LocalDateTime startTime,
                                                    LocalDateTime endTime, String gesturePoint) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        SignActivity activity = new SignActivity();
        activity.setTeacherId(teacher.getId());
        activity.setType(SignActivity.SignType.gesture); // 使用新增的手势签到类型
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setSecret(gesturePoint); // 将手势坐标存储到secret字段

        signActivityMapper.insert(activity);
        return ApiResponse.success("创建九宫格手势签到活动成功", activity);
    }
    @Transactional
    public ApiResponse<?> createLocationSignActivity(String jwt, LocalDateTime startTime, LocalDateTime endTime,
                                                     Double longitude, Double latitude, Integer radius) {
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        SignActivity activity = new SignActivity();
        activity.setTeacherId(teacher.getId());
        activity.setType(SignActivity.SignType.location);
        activity.setStartTime(startTime);
        activity.setEndTime(endTime);
        activity.setSecret(longitude + "," + latitude + "," + radius);

        signActivityMapper.insert(activity);
        return ApiResponse.success("创建位置签到活动成功", activity);
    }
    public ApiResponse<?> getSignRecordsForExport(String jwt, Integer activityId) {
        // 验证教师身份
        User teacher = validateTeacher(jwt);
        if (teacher == null) {
            return ApiResponse.error("无效的教师账号");
        }

        // 获取签到记录数据
        List<Object[]> signRecords = signActivityMapper.getSignRecordsForExport(activityId, teacher.getId());
        return ApiResponse.success(signRecords);
    }
} 